package com.moon;

import java.util.List;
import java.util.Set;

import cn.yueliangbaba.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.RequestParams;
import com.sys.DemoApp;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.ToastUtil;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

public class SetPwdActivity extends BaseActivity implements OnClickListener{

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_set_pwd);
		
		findViewById(R.id.left).setOnClickListener(this);
		((TextView) findViewById(R.id.center)).setText("设置密码");
		findViewById(R.id.next).setOnClickListener(this);
	}
	
	private void sendRequest() {
		String pwd0 = ((EditText)findViewById(R.id.phone)).getText().toString();
		String pwd1 = ((EditText)findViewById(R.id.code)).getText().toString();
		
		if(pwd0.length() == 0 || !pwd0.equals(pwd1))
		{
			ToastUtil.showToastWithAlertPic("密码不能为空/密码不一致");
			return;
		}
		
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);
				if (ruser.getString("statusCode").equals("0")) {
					ToastUtil.showToastWithAlertPic("激活成功，请登录");
					
					List<Activity> list = ((DemoApp) getApplicationContext()).getActivityList();
					int count = list.size();
					for (int i = count - 2; i >= 0; i--) {
						Activity act = list.get(i);
						if(!act.getClass().getName().contains("LoginActivity"))
						{
							act.finish();
						}
					}
					
					finish();
				}
				else 
				{
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
			
			@Override
			public void onFailure(Throwable ble) {
				super.onFailure(ble);
				ToastUtil.showToastWithAlertPic("网络状况不佳，请稍后重试...");
			}
		};
		
		JSONObject param = JSON.parseObject(getIntent().getStringExtra("param"));

		RequestParams params = new RequestParams();
		params.put("id", getIntent().getExtras().getInt("id"));
		params.put("password", pwd1);
		
		Set<String> keys = param.keySet();
		for(String key : keys)
		{
			String value = param.getString(key);
			params.put("identity[" + key + "]", value);
		}
		
		MgqRestClient.get("member_active", params, loginHandler);
	}

	@Override
	public void onClick(View arg0) {
		if(R.id.left == arg0.getId()) finish();
		else sendRequest();
	}
}
